package JavaEE;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
// 模拟实现一个"简单的线程池"
// 只实现"固定线程数目"的线程池
class MyFixedThreadPool {
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    // 线程池中有n个线程.
    public MyFixedThreadPool(int n) {
        // 当线程池被创建时,n个线程就开始运作
        // 这里我们创建出n个线程并start
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                try {
                    // 代表每一个线程都将不停的从"阻塞队列"中"获取任务并且执行任务"
                    while (true) {
                        Runnable task = queue.take();
                        task.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            // 将线程启动
            t.start();
        }
    }

    // 将一个任务加入到阻塞队列中.
    public void submit(Runnable task) throws InterruptedException {
        queue.put(task);
    }
}
public class MyThreadPool {
    public static void main(String[] args) {
        MyFixedThreadPool threadpool = new MyFixedThreadPool(4);
        for(int i = 0;i < 100;i++){
            int num = i;
            try {
                threadpool.submit(() -> {
                    System.out.println("执行一个任务:" + num);
                });
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
